import React, { useCallback, useMemo, useRef, useState} from 'react';
import {
  FullPage,
  Layout,
  Panel,
  ProjectTree,
  AsyncTree,
  QueryPanel,
  flexStyle,
  udp,
  useRefCallback,
  useRefs
} from '@cscec/udp-ui';
import type { IProps } from './interface';
import { LIST_TREE_TYPE } from '@/pages/editor/lowcode/data';
import IndicatorCenterCard from '@/components/editor/plugin/portal/IndicatorCenter/component/indicatorCenterCard';
import { getRequestByConfig } from '@/pages/customForm/service';

function getOrgTreeDefParams(orgTreeType: string) {
  switch (orgTreeType) {
    case LIST_TREE_TYPE.ORG:
      return {
        // containPlatformAdmin: true,
        // containDept: false,
        cuId: '', // 单元ID
        containNoRight: true, //是否包含无权限组织
        adminId: '', // 管理员ID
        treeNo: '' // 树结构类型编号, 用户自定义，默认值lg系统树
      };
    case LIST_TREE_TYPE.DEPT:
      return {
        treeNo: '' // 树结构类型编号, 用户自定义，默认值lg系统树
        // containDept: true
      };
    case LIST_TREE_TYPE.PROJECT:
      return {
        enableManagerControl: false, // 启用管理员权限控制
        dataAccessAuth: true, // 开启数据权限控制
        orgInnerType: '2', // 组织树的权限类型： 1 登录组织权限、2数据查询组织权限
        containLowCu: true, // 包含单元
        containDept: false, // 包含部门
        containProject: false, // 包含项目
        enableManagerContrl: false, // 启用管理员数据权限
        orgNo: '' // 只显示此组织
      };
    default:
      return { type: 'project' };
  }
}

function getOrgTreeDefRequest(orgTreeType: string) {
  let url = '';
  switch (orgTreeType) {
    case LIST_TREE_TYPE.ORG:
      url = '/basedata/org/getOrgTreeByAdminNo';
      break;
    case LIST_TREE_TYPE.DEPT:
      url = '/basedata/orgTree/getOrgDeptTree';
      break;
    case LIST_TREE_TYPE.PROJECT:
    default:
      url = '/basedata/org/getCompleteOrgTree';
  }
  return async (data: Object) => {
    const res = await udp.request.get({
      url: url,
      data
    });
    if (res?.code === 0) {
      return res?.data ?? [];
    } else {
      return [];
    }
  };
}

async function getData({ source, env, params, microServiceName}: { env: any; source?: any; params: any, microServiceName: string }) {
  let options = source;

  if (env.session === 'render') {
    // 渲染时，如果未配置api，则使用默认api
    if (!options) {
      options = {
        method: 'get',
        url: '/customForm/customPC/getList'
      };
    }
    const localRequest = getRequestByConfig(microServiceName, options);
    const result = await localRequest({ params: params });
    if(result.code == 0){
      return result.data || {list: [], total: 0};
    }
    udp.alert(result.message);

    // if (udp.isString(options)) {
    //   options = { url: options, data: params };
    // } else {
    //   options.data = { ...options.data, ...params };
    // }
    // const { status, msg, data } = await env.fetcher(options);
    // if (status === 0) {
    //   return data || { list: [], total: 0 };
    // }
    // udp.alert(msg);
  }
  return { list: [], total: 0 };
}

/**
 * 通用帮助
 * @param param
 * @returns
 */
export default function ListPage({
  busType,
  masterTableName,
  showProjectOrgTree,
  orgTreeType = LIST_TREE_TYPE.PROJECT,
  requestList,
  requestDelete,
  render,
  table,
  toolbar,
  style,
  source,
  extraData,
  env
}: IProps) {
  console.log('[debug] listPage fc: ', arguments);
  const [getRef] = useRefs();
  const globalProject = useRef<any>(null);
  if(env.session === 'render'){ //只渲染时，disabled所有列
    Array.isArray(table) ? table.forEach((item) => {
      item?.columns.forEach((ii) => {
        ii.disabled = true;
      })
    }) : table?.columns?.forEach((ii) => {
      ii.disabled = true;
    });
  }

  // 列表查询
  const listRequest = useRefCallback(({ pageSize, pageIndex, ...queryPanelFilter }) => {
    const node = getRef('tree').current?.getApi()?.getSelectedNodes?.()?.[0];
    const params: any = { bizCode: busType, pageNum: pageIndex, pageSize, queryPanelFilter };
    if (node || globalProject.current) {
      params.treeNode = node ? { code: node.code, leafType: node.leafType } : globalProject.current;
    }
    return getData({ source: requestList, env, params, microServiceName: extraData?.microServiceName });
  });

  const onSelectedChange = useRefCallback(() => {
    getRef('grid').current.getApi().refreshData();
  });

  const showTree = () => {
    if (showProjectOrgTree) {
      const projCode = udp.getUser()?.projCode;
      if (projCode) {
        globalProject.current = { code: projCode, leafType: 'PROJECT' };
        return false;
      }
      return true;
    }
    return false;
  };

  const convertNode = useRefCallback((node, levelIndex) => {
    // 默认选中第一个节点
    if (levelIndex.level === 0 && levelIndex.index === 0) {
      node.isSelected = true;
    }
    return node;
  });

  const orgTreeDefParams = useMemo(() => getOrgTreeDefParams(orgTreeType), [orgTreeType]);
  const orgTrerDefRequest = useCallback(getOrgTreeDefRequest(orgTreeType), [orgTreeType]);
  
  const [ indicatorCardParams, setIndicatorCardParams] = useState({});
  const isLocal = useRef(location.hostname == 'localhost');

  return (
    <Layout
      direction="row"
      autoFit
      style={{ padding: 'var(--outer-margin, 16px)', backgroundColor: 'var(--body-background, #f0f2f5)' }}
    >
      {showTree() && (
        <Layout.Slider size={200} style={{ margin: '0 var(--inner-margin, 16px) 0 0' }}>
          <Panel title="项目组织树" autoFit bodyStyle={{ padding: 'var(--inner-padding, 8px)' }}>
            {/* <ProjectTree defaultChange={false} id={`${busType}_tree`} ref={getRef('tree')} onSelectedChange={onSelectedChange} /> */}
            <AsyncTree
              ref={getRef('tree')}
              id={`${busType}_tree`}
              key={orgTreeType}
              request={orgTrerDefRequest}
              params={orgTreeDefParams}
              convertNode={convertNode}
              onSelectedChange={onSelectedChange}
              defaultChange={false}
            />
          </Panel>
        </Layout.Slider>
      )}
      <Layout.Flex direction="column">
        {busType && 
          <QueryPanel id={`${busType}_query`} 
              pageId={busType || ''} 
              gridRef={getRef('grid')} 
              onSearch={(_, values) => setIndicatorCardParams(values)}
          />}
        {busType && extraData?.capacity?.metricsFlag == 1 && 
          <div>
            {isLocal ? <div className="test_123"> 本地环境不展示指标中心 </div> :
              <IndicatorCenterCard
                data={{
                  params: indicatorCardParams,
                  userInfo: udp.getUser(),
                  bizCode: busType,
                  oType: udp.getQueryValue('oType'),
                  controlCategory: 1,
                  page: extraData.page
                }}
              />
            }
          </div>
        }
        <FullPage
          className="flex-column"
          style={{ flex: 1, height: 0, backgroundColor: 'var(--component-background)' }}
        >
          <Layout style={flexStyle({ paddingBottom: 0 })}>
            {toolbar &&
              render('toolbar', toolbar, {
                id: `${busType}_toolbar`,
                style: {
                  ...toolbar.style,
                  padding: '0 0 var(--inner-padding, 8px) 0',
                  minHeight: 40,
                  rightName: busType
                }
              })}
            <Layout.Flex>
              {table &&
                render('table', table, {
                  tableProps: {
                    ...(table[0] || table).tableProps,
                    id: `${busType}_${masterTableName}`,
                    ref: getRef('grid'),
                    request: listRequest
                  }
                })}
            </Layout.Flex>
          </Layout>
        </FullPage>
      </Layout.Flex>
    </Layout>
  );
}
